<template>
	<view class="section-study">
		<view class="top" style="z-index: 2;" :style="{'padding-top': paddingTop}">
			<uni-icons style="margin-left: 30rpx;" type="left" size="25" color="#2c2c2c" @click="toBackPage">
			</uni-icons>

			<view style="margin-left: 30rpx;">
				{{sectionInfo.name}}
			</view>
		</view>

		<view class="content" id="mark" v-if="sectionInfo.type == 0">

			<view class="content-item">

				<view class="content-title">
					<view>本节引入</view>
					<uni-icons @click="gotoSectionContentComment(sectionInfo.linkId)" type="chatboxes" size="25"
						color="#595959"></uni-icons>
				</view>

				<view style="padding: 0 25rpx;">
					<view v-html="sectionInfo.content"></view>
				</view>
			</view>

			<view class="content-item" v-for="(content,index) in sectionContents">

				<view class="content-title">
					<view>{{content.name}}</view>
					<uni-icons @click="gotoSectionContentComment(content.id)" type="chatboxes" size="25"
						color="#595959"></uni-icons>
					<!-- 					<view>
						<uni-icons @click="gotoSectionContentComment(content.id)" v-if="index === 1" type="chatboxes" size="25" color="#595959"></uni-icons>
						<uni-icons @click="gotoSectionContentComment(content.id)" v-else type="chatboxes" size="25" color="#d3d3d3"></uni-icons>
					</view> -->

				</view>

				<view v-if="content.type == 0" style="padding: 0 25rpx;">
					<view v-html="content.content"></view>
				</view>

				<view style="z-index: 2;" v-if="content.type == 1">
					<video id="myVideo" :src="content.video.playUrl" @error="videoErrorCallback" @play="onStartPlay"
						@pause="onPause" @timeupdate="handleTimeupdate" @fullscreenchange="fullScreenChange"
						poster="https://www.cdn.kxcdedu.top/01378270801f71ed809e6723b78e0102/snapshots/89ff6147c21f4d859fb82cfa003a8bf6-00005.jpg"
						:initial-time="lastTime" enable-danmu controls page-gesture
						style="width: 650rpx;height: 380rpx;margin-top: 10rpx;margin-left: 25rpx;">
					</video>
				</view>

				<view v-if="content.type == 2">
					<view class="popup-content" style="padding: 0 25rpx;">
						<view class="title">{{content.problem.description}}</view>
						<view class="option" v-for="(option,index) in content.problem.options" :key="option.id"
							@click="handleSelectedOption(index)">
							<view class="option-char" :class="[
									{'selected-option-char':selectedOption === index},
									{'selected-wrong-option':isWrong(selectedOption,content.problem.answer) && selectedOption === index}]"
								style="display: inline-block;">
								{{choosesLeft[index]}}
							</view>
							<view class="option-name" style="display: inline-block;">
								{{option}}
							</view>
						</view>
						<!-- 						<view style="display: flex;flex-direction: row;justify-content: center;">
							<view class="submit-button" @click="answerQuestionConfirm()">继续</view>
						</view> -->
					</view>
				</view>
			</view>
		</view>

		<view class="content" v-if="sectionInfo.type == 1">
			<h3>{{sectionInfo.exam.title}}</h3>
			<view class="content-item">
				<view v-html="sectionInfo.exam.description"></view>
			</view>

			<view class="content-item">
				<view>往期提交</view>
				<view style="display: flex;flex-direction: row;align-items: center;width: 100%;" class="record">
					<view style="width: 20%;">次数</view>
					<view style="width: 20%;">分数/总分</view>
					<view style="width: 40%;">开始时间</view>
					<view style="width: 20%;display:flex;justify-content: flex-end">操作</view>
				</view>
				<view v-for="(record,recordIndex) in sectionInfo.examRecords" :key="recordIndex">
					<view style="display: flex;flex-direction: row;align-items: center;" class="record">
						<view style="width: 20%;">第{{recordIndex+1}}次</view>
						<view style="width: 20%;">
							<view v-if="record.status > 0">{{record.score}}/{{sectionInfo.exam.totalScore}}
							</view>
						</view>
						<view style="width: 40%;">{{record.gmtCreate | gmtToDate}}</view>
						<view @click="gotoTestRecord(record.id)"
							style="width: 20%;display:flex;justify-content: flex-end;color: #357FF8;">
							{{record.status > 0 ? "查看" : "继续" }}
						</view>
					</view>
				</view>
			</view>

			<view class="content-item" style="margin-top: 200rpx;">
				<button type="primary" @click="gotoTest()">开始测试</button>
			</view>
		</view>

		<view class="bottom">
			<view class="bottom-item">
				<uni-icons type="bars" size="30" color="#2c2c2c" @click="showMenu"></uni-icons>
				<view>目录</view>
			</view>

			<view class="bottom-item">
				<uni-icons type="circle" size="30" color="#2c2c2c"></uni-icons>
				<view>深色</view>
			</view>

			<view class="bottom-item">
				<uni-icons :class="{'talk-button' : isTalking}" type="circle-filled" size="30" color="#2c2c2c"
					@click="showTalks"></uni-icons>
				<view>箴言</view>
			</view>

			<view class="bottom-item">
				<uni-icons type="paperplane" size="30" color="#2c2c2c"></uni-icons>
				<view>转发</view>
			</view>
		</view>

		<uni-popup ref="menu" type="bottom">
			<view
				style="width: 100%;height: 880rpx;background-color: white;border-radius: 20rpx 20rpx 0 0;padding-top: 40rpx;">
				<view class="catalogs">
					<view v-for="(catalog,index) in chapters" :key="catalog.id">
						<view class="catalog" @click="handleIsShowIndex(index)">
							<view>
								{{catalog.name}}
							</view>
							<view>
								<uni-icons type="bottom" size="20" color="#ADAAAA" v-if="!isShowIndex[index]">
								</uni-icons>
								<uni-icons type="top" size="20" color="#ADAAAA" v-if="isShowIndex[index]">
								</uni-icons>
							</view>
						</view>
						<view v-if="isShowIndex[index]" class="section">
							<view v-for="(section,index) in catalog.sections" :key="index" style="margin-top:25rpx;">
								<view @click="gotoStudy(section.id)"
									style="margin-left: 20rpx;display: flex;flex-direction: row;justify-content: space-between;">
									<view style="width: 84%;">{{section.name}}</view>
									<view style="width: 16%;text-align: right;color: #5DACB1;">
										{{section.progress ? section.progress : 0}}%</view>
								</view>

								<view v-if="section.type == 0"
									style="display: flex;flex-direction: row;align-items: center;margin-left: 40rpx;margin-top:15rpx;">
									<view
										style="height: 100%;display: flex;flex-direction: row;align-items: center;width: 12%;">
										<view class="type">文本</view>
									</view>
									<view style="width: 72%;">
										<view class="name">本节引入</view>
									</view>
									<view style="width: 16%;">
										<!-- <view style="text-align: right;color: #357FF8;">{{content.progress}}%</view> -->
									</view>
								</view>

								<view v-for="(content,contentIndex) in section.contents" :key="content.id">
									<view
										style="display: flex;flex-direction: row;align-items: center;margin-left: 40rpx;margin-top:15rpx;">
										<view
											style="height: 100%;display: flex;flex-direction: row;align-items: center;width: 12%;">
											<view class="type">{{contentType[content.type]}}</view>
										</view>
										<view style="width: 72%;">
											<view class="name">{{content.name}}</view>
										</view>
										<view style="width: 16%;">
											<!-- <view style="text-align: right;color: #357FF8;">{{content.progress}}%</view> -->
										</view>
									</view>
								</view>

							</view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>

		<uni-popup ref="talking" type="bottom">
			<view style="width: 100%;margin-bottom: 200rpx;" v-if="currentTalks && currentTalks.length > 0">
				<view v-for="talk in currentTalks" class="talk">
					<view class="talk-content">{{talk.content}}</view>
					<view class="button">
						<uni-icons type="hand-down" size="25" color="#ffffff"></uni-icons>
						<uni-icons type="hand-up" size="25" color="#ffffff"></uni-icons>
					</view>
				</view>
			</view>

			<view style="width: 100%;background-color: #5f5f5f;">
				<view class="talk-input">
					<view
						style="display: flex;flex-direction: column;justify-content: space-between;align-items: center;height: 120rpx;width: 80rpx;">
						<view style="color: #FFFFFF;">{{timeTypes[talkInput.time]}}</view>
						<uni-icons @click="changeTimeType()" type="circle-filled" size="30" color="#2c2c2c"></uni-icons>
					</view>
					<textarea :show-confirm-bar="false" style="width: 540rpx;height: 150rpx;color:#d8d8d8"
						v-model="talkInput.content" type="text" :focus="talkInputFocus" placeholder="写箴言"></textarea>
					<view style="color: white;" @click="addTalk()">发表</view>
				</view>
			</view>
		</uni-popup>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				sectionInfo: {},
				sectionContents: [],
				selectedOption: null,

				videoContext: null,
				lastTime: 0,



				windowHeight: 0,
				progress: 0,
				isTalking: false,
				
				timeTypes: ["3s", "10s", "1m", "5m", "10m", "20m"],
				timeTypeMiles: [3, 10, 60, 300, 600, 1200],
				currentTimeIndex:-1,


				choosesLeft: ["A", "B", "C", "D", "E", "F"],

				talkContent: [],

				talks: [],
				talkMap: [],


				currentTalks: [],


				talkInputFocus: false,
				talkInput: {
					time: 0,
					content: ""
				},
				chapters: [],
				contentType: ["文本", "视频", "题目"],
				isShowIndex: [true, true],


				paddingTop: null
			}
		},
		onUnload() {
			console.log("退出")
			this.updateProgress()
		},
		onPageScroll(e) {
			if (this.windowHeight == 0) {
				const query = uni.createSelectorQuery().in(this);
				query.select('#mark').boundingClientRect(data => {
					this.windowHeight = data.height
				}).exec();
			} else {
				let progress = Math.round(Math.min(e.scrollTop / (this.windowHeight - 690), 1) * 100)
				this.progress = progress
				if (this.talkMap.get(progress)) {
					this.setTalkWait(this.talkMap.get(progress),progress)
				} else {
					this.isTalking = false
					this.currentTimeIndex = -1
					this.currentTalks = []
				}
			}
		},
		onLoad(options) {
			var sectionId = options.sectionId
			this.getSectionStudyInfo(sectionId)

			// 调整搜索位置
			// #ifdef MP-WEIXIN
			// 1.获取屏幕可使用宽度
			let windowWidth = uni.getSystemInfoSync().windowWidth;
			// 3.获取胶囊按钮位置信息
			const menuButton = uni.getMenuButtonBoundingClientRect();
			// // 5.导航栏与状态栏拉开距离  margin-top: statusBarTop + 'rpx';
			this.paddingTop = menuButton.top * (750 / windowWidth) + 'rpx';
			// #endif
		},
		methods: {
			getSectionStudyInfo(id) {
				this.$api.getSectionStudyInfo({
					id
				}).then(res => {
					this.sectionInfo = res.data.sectionInfoVO

					// TODO 页面滚动到具体的进度

					// 加载箴言
					this.talks = res.data.talks
					let talkMap = new Map()
					let i = 0
					for (; i < this.talks.length; i++) {
						let arr = talkMap.get(this.talks[i].progress)
						if (arr) {
							if (arr[this.talks[i].time]) {
								arr[this.talks[i].time].push(this.talks[i])
							} else {
								arr[this.talks[i].time] = []
								arr[this.talks[i].time].push(this.talks[i])
							}
						} else {
							arr = []
							arr[this.talks[i].time] = []
							arr[this.talks[i].time].push(this.talks[i])
						}
						talkMap.set(this.talks[i].progress, arr)
					}
					this.talkMap = talkMap

					console.log("初始检验", this.talkMap.get(0))

					if (this.talkMap.get(0)) {
						this.setTalkWait(this.talkMap.get(0),0)
					}

					this.sectionContents = res.data.sectionContentVOList
					this.videoContext = uni.createVideoContext("myVideo", this);
				})
			},
			
			setTalkWait(talkArr,progress){
				let i;
				for(i = 0;i<6;i++){
					if(talkArr[i]){
						console.log("触发",i,talkArr[i])
						
						
						switch(i){
							case 0:
							setTimeout(() => {
								// 只有固定的时间之后还在这个进度的才能触发
								if (this.progress == progress) {
									this.showTalking(0)
								}
							}, this.timeTypeMiles[i] * 1000)
							break;
							
							case 1:
							setTimeout(() => {
								// 只有固定的时间之后还在这个进度的才能触发
								if (this.progress == progress) {
									this.showTalking(1)
								}
							}, this.timeTypeMiles[i] * 1000)
							break;
							
							case 2:
							setTimeout(() => {
								// 只有固定的时间之后还在这个进度的才能触发
								if (this.progress == progress) {
									this.showTalking(2)
								}
							}, this.timeTypeMiles[i] * 1000)
							break;
							
							case 3:
							setTimeout(() => {
								// 只有固定的时间之后还在这个进度的才能触发
								if (this.progress == progress) {
									this.showTalking(3)
								}
							}, this.timeTypeMiles[i] * 1000)
							break;
							
							case 4:
							setTimeout(() => {
								// 只有固定的时间之后还在这个进度的才能触发
								if (this.progress == progress) {
									this.showTalking(4)
								}
							}, this.timeTypeMiles[i] * 1000)
							break;
							
							case 5:
							setTimeout(() => {
								// 只有固定的时间之后还在这个进度的才能触发
								if (this.progress == progress) {
									this.showTalking(5)
								}
							}, this.timeTypeMiles[i] * 1000)
							break;
						}
					}
				}
			},
			
			showTalking(currentTimeIndex){
				this.isTalking = true
				this.currentTimeIndex = currentTimeIndex
				setTimeout(() => {
					this.isTalking = false
					this.currentTimeIndex = -1
				}, 5 * 1000)
			},

			updateProgress() {
				this.$api.updateProgress({
					sectionId: this.sectionInfo.id,
					progress: this.progress
				})
			},


			showMenu() {
				this.$api.getDetailCourseDirs({
					courseId: this.sectionInfo.courseId
				}).then(res => {
					console.log("目录", res)
					this.chapters = res.data;
				})

				this.$refs.menu.open('bottom')
			},

			changeTimeType() {
				console.log("触发")
				this.talkInput.time = (this.talkInput.time + 1) % 6
			},
			addTalk() {
				this.$api.addTalk(this.talkInput).then(res => {
					uni.showToast({
						title: "成功刻入~"
					})
					this.talking = false
					this.$refs.talking.close('bottom')
				})
			},




			playVideo() {
				this.videoPlaying = true;
				this.videoContext.play()
			},
			onPause() {
				this.videoPlaying = false;
				console.log('暂停视频')
			},
			onStartPlay() {
				console.log('播放视频')
			},
			fullScreenChange() {

			},
			videoErrorCallback() {

			},
			handleReady(e) {
				console.log(`ready`, e);
			},
			handleTimeupdate(e) {
				// let time = this.$refs.VueAliplayerV2.getCurrentTime();
			},














			gotoSectionContentComment(contentId) {
				this.updateProgress()
				uni.navigateTo({
					url: '/pages_being/course/section-comment?contentId=' + contentId
				})
			},

			gotoStudy(sectionId) {
				this.updateProgress()
				uni.navigateTo({
					url: '/pages_being/course/section-study?sectionId=' + sectionId
				})
			},
			gotoTest() {
				// 开始测试并生成记录
				this.$api.createExamRecord({
					examId: this.sectionInfo.linkId
				}).then(res => {
					uni.navigateTo({
						url: '/pages_being/course/exam-detail?recordId=' + res.data
					})
				})
			},

			toBackPage() {
				uni.navigateBack()
			},
			showTalks() {
				if (!this.isTalking) {
					this.talkInputFocus = true
				}
				// console.log("获取的数据", this.talkMap)
				this.currentTalks = this.talkMap.get(this.progress)[this.currentTimeIndex]
				this.isTalking = false
				console.log("弹出前", this.progress, this.currentTimeIndex, this.currentTalks)
				this.$refs.talking.open('bottom')
				this.talkInput = {
					time: 0,
					content: "",
					sectionId: this.sectionInfo.id,
					progress: this.progress
				}
			},
			handleIsShowIndex(index) {
				this.isShowIndex[index] = !this.isShowIndex[index]
				this.$forceUpdate()
			},
			handleSelectedOption(answer) {
				this.selectedOption = answer
			},
			isWrong(answer, rightAnswer) {
				return parseInt(answer) !== parseInt(rightAnswer)
			},
		},
		filters: {
			gmtToDate(gmt) {
				let fmt = "YYYY-mm-dd HH:MM";
				let date = new Date(parseInt(gmt));
				let ret;
				const opt = {
					"Y+": date.getFullYear().toString(), // 年
					"m+": (date.getMonth() + 1).toString(), // 月
					"d+": date.getDate().toString(), // 日
					"H+": date.getHours().toString(), // 时
					"M+": date.getMinutes().toString(), // 分
					"S+": date.getSeconds().toString(), // 秒
					// 有其他格式化字符需求可以继续添加，必须转化成字符串
				};
				for (let k in opt) {
					ret = new RegExp("(" + k + ")").exec(fmt);
					if (ret) {
						fmt = fmt.replace(
							ret[1],
							ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
						);
					}
				}
				return fmt;
			}
		}



	}
</script>

<style scoped lang="scss">
	.section-study {
		background-color: #FFFFFF;

		.top {
			position: sticky;
			top: 0;
			background-color: white;
			border-bottom: solid thin #d1d1d1;


			width: 100%;
			height: 80rpx;
			display: flex;
			flex-direction: row;
			align-items: center;
			padding-top: 100rpx;

			// #ifdef H5
			padding-top: 40rpx;
			// #endif
		}

		.content {
			width: 700rpx;
			min-height: 1400rpx;
			margin-left: 25rpx;
			padding-top: 40rpx;



			display: flex;
			flex-direction: column;
			align-items: center;

			.content-title {
				width: 650;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;


				font-size: 36rpx;
				font-weight: bold;
				margin: 10rpx 25rpx;
			}

			.content-item {
				width: 100%;
				margin-bottom: 40rpx;

				line-height: 50rpx;
				letter-spacing: 4rpx;

				/deep/ p {
					margin: 20rpx 0;
				}


				.record {
					color: #838080;
					margin-top: 8rpx;
					font-size: 28rpx;
				}

			}

			.popup-content {
				display: flex;
				flex-direction: column;
				align-items: flex-start;
				justify-content: center;

				.title {
					font-size: 32rpx;
				}

				.option {
					margin: 20rpx 0;
				}

				.option-char {
					width: 60rpx;
					text-align: center;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 50%;
					background-color: #E4E4E4;
				}

				.selected-option-char {
					background-color: #619DFF;
					color: #ffffff;
				}

				.selected-wrong-option {
					background-color: #ff5457;
					color: #ffffff;
				}


				.option-name {
					margin-left: 20rpx;
				}

				.popup-button {
					width: 160rpx;
					text-align: center;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 50rpx;
					color: #ffffff;
				}

				.cancel {
					background-color: #ADAAAA;
				}

				.submit {
					background-color: #619DFF;
					margin-left: 110rpx;
				}


				.submit-button {
					width: 160rpx;
					text-align: center;
					height: 60rpx;
					line-height: 60rpx;
					background-color: #619DFF;
					color: #ffffff;
					border-radius: 50rpx;
				}

				.answer {
					width: 540rpx;
					background-color: #F6F6F6;
					border-radius: 20rpx;
					padding: 20rpx;
					margin-bottom: 30rpx;
				}


			}

		}

		.bottom {
			position: sticky;
			bottom: 0;
			z-index: 5;
			background-color: white;


			width: 100%;
			height: 90rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-around;
			align-items: center;
			padding: 20rpx 0;

			.bottom-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				font-size: 24rpx;

			}

			.talk-button {
				animation: twinkle 0.5s infinite alternate;
			}

			@keyframes twinkle {
				0% {
					opacity: .0.8;
				}

				100% {
					opacity: 0;
				}
			}
		}

		.catalogs {
			display: flex;
			flex-direction: column;
			width: 670rpx;
			margin: 0 40rpx 40rpx 40rpx;
			height: 840rpx;
			overflow-y: scroll;

			.catalog {
				display: flex;
				flex-direction: row;
				margin-top: 40rpx;
				justify-content: space-between;

			}
		}

		.talk-input {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: flex-end;
			width: 700rpx;
			padding: 25rpx;
		}

		.talk {
			width: 670rpx;
			margin-left: 40rpx;
			border-radius: 20rpx;
			background-color: #5f5f5f;

			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx 0;
			margin-bottom: 30rpx;


			.talk-content {
				color: white;
				width: 610rpx;
				margin: 0 30rpx 20rpx 30rpx;
				padding-bottom: 20rpx;

				border-bottom: solid thin #909090;
			}

			.button {
				display: flex;
				flex-direction: row;
				justify-content: space-between;

				width: 350rpx;
			}
		}
	}





	image {
		width: 100%;
		height: 100%;
	}
</style>